import React, { useState, useEffect, useRef } from 'react';

const SpecialTextContentEditable = ({ contentState, entityKey, onEntityChange }) => {
  const entity = contentState.getEntity(entityKey);
  const entityData = entity.getData();
  const [value, setValue] = useState(entityData.text);
  const contentEditableRef = useRef(null);

  useEffect(() => {
    setValue(entityData.text);
  }, [entityData.text]);

  useEffect(() => {
    const wrapperElement = contentEditableRef.current.parentElement;
    wrapperElement.addEventListener('keydown', handleKeyDown);

    return () => {
      wrapperElement.removeEventListener('keydown', handleKeyDown);
    };
  }, []);


  const style = {
    backgroundColor: 'rgba(0, 0, 255, 0.1)',
    // padding: '0 2px',
    border: 'none',
    outline: 'none',
    // display: 'inline-block',
  };

  const handleChange = () => {
    const newValue = contentEditableRef.current.textContent;
    console.log("newValue----->", newValue)
    setValue(newValue);
  };

  const handleKeyDown = (e) => {
    // if (e.key === 'Enter') {
    //   e.preventDefault();
    //   contentEditableRef.current.blur();
    // }
    console.log("测试", e.code)
    e.preventDefault();
    e.stopPropagation();
  };

  const handleMouseDown = (e) => {
    e.stopPropagation();
  };

  const onTextEditorFocus = (e) => {
    console.log("onTextEditorFocus---->聚焦")
  }

  const onTextEditorBlur = () => {
    console.log("onTextEditorBlur---->失去焦点")
    if (onEntityChange) {
      onEntityChange(entityKey, value);
    }
  };

  return (
    <span
      ref={contentEditableRef}
      contentEditable
      suppressContentEditableWarning
      onBlur={onTextEditorBlur}
      onFocus={onTextEditorFocus}
      onKeyDown={handleKeyDown}
      onMouseDown={handleMouseDown}
      onInput={handleChange}
      style={style}
      tabIndex={0}
    >
      {value}
    </span>
  );
};


export default SpecialTextContentEditable;